<?php 

namespace Api\Controller\V2;

use Api\Event\CacheEvent;
use Api\Event\LocalClientEvent;
// +----------------------------------------------------------------------
// | 文件 V2BaseController.class.php
// +----------------------------------------------------------------------
// | 说明 只封装必要的方法
// +----------------------------------------------------------------------
// | 
// +----------------------------------------------------------------------
// | Author: 谢赤心 Legend. <xcx_legender@qq.com>
// +----------------------------------------------------------------------


abstract class V2BaseController
{

    public function __construct()
    {

    }

    /**
     * 错误的调用
     * @param  [type] $method [description]
     * @param  [type] $args   [description]
     * @return [type]         [description]
     */
    public function __call($method, $args)
    {
        error(404);
    }

    /**
     * 封装的检查用户登陆
     * @return [type] [description]
     * 3-5ms -> mysql 5-10ms
     */
    protected function checkLogin()
    {
        $appToken = request('appToken');
        if (!$appToken){
            error(501, '用户未登录');
        }

        $redis = CacheEvent::instance(1);
        $key = "IMBA.USER.UID.TOKEN.{$appToken}";
        $uid = $redis->get($key);
        if (!$uid) {
            $map = array(
                'app_token' => trim($appToken),
            );
            $res = service('Token')->where($map)->limit(1)->find();
            $uid = $res ? $res['uid'] : 0;
            if ($uid) {
                $redis->setex($key, 60, $uid);
            }
        }

        if ($uid){
            request('uid', (int)$uid);
            return true;
        }
        error(501, '用户未登录');
    }

    /**
     * 设置并检查用户信息 主要是用户昵称
     * @param [type] $uid [description]
     * 5-10ms
     */
    protected function checkUser($uid)
    {
        $service = service('Users');
        $user = $service->find($uid);
        if (!$user || $user['status'] != 1){
            error(502, '未设置昵称');
        }
        if (!$user['nickname']){
            error(502, '未设置昵称');
        }
        request('user', $user);
    }

    /**
     * 封装的获取配置信息 如果接口有使用那么需要在接口方法前几行必须调用
     * @return [type] [description]  
     * 3ms
     */
    protected function loadConfig()
    {
        static $loaded = false;
        if (!$loaded){
            $Redis = CacheEvent::instance(0);
            load_config($Redis);
            unset($Redis);
            $loaded = true;
        }
    }

}
